//Spinner 配置项
var opts = {
    lines: 7 // The number of lines to draw
    , length: 0 // The length of each line
    , width: 20 // The line thickness
    , radius: 20 // The radius of the inner circle
    , scale: 0.25 // Scales overall size of the spinner
    , corners: 1 // Corner roundness (0..1)
    , color: '#333' // #rgb or #rrggbb or array of colors
    , opacity: 0.25 // Opacity of the lines
    , rotate: 0 // The rotation offset
    , direction: 1 // 1: clockwise, -1: counterclockwise
    , speed: 1 // Rounds per second
    , trail: 10 // Afterglow percentage
    , fps: 20 // Frames per second when using setTimeout() as a fallback for CSS
    , zIndex: 2e9 // The z-index (defaults to 2000000000)
    , className: 'spinner' // The CSS class to assign to the spinner
    , top: 'auto' // Top position relative to parent
    , left: '50%' // Left position relative to parent
    , shadow: false // Whether to render a shadow
    , hwaccel: true // Whether to use hardware acceleration
};

//set post timeout
var timeout = null;

/**
 * 顶部alert提示
 * @param {type} message
 * @param {type} warn
 * @param {type} callback
 * @returns {undefined}
 */
function Alert(message, warn, callback) {
    warn = warn || false;
    var node = $('<div class="alert" id="__alert__"></div>');
    if (warn) {
        node.addClass('alert-danger');
        node.removeClass('alert-success');
    } else {
        node.removeClass('alert-danger');
        node.addClass('alert-success');
    }
    node.html(message);
    $('body').append(node);
    node.css('left', ($('body').width() - node[0].clientWidth) / 2 + 'px').slideDown();
    window.setTimeout(function () {
        node.slideUp(300, function () {
            if (typeof callback === 'function') {
                callback();
            }
            $('#__alert__').remove();
        });
    }, 5000);
}

/**
 * login form validation
 * @returns {boolean}
 */
function check_form() {
    btn_submit=$("#btn_submit");
    user_name=$("#user_name");
    user_pass=$("#user_pass");
    name_group=user_name.parent().parent();
    pass_group=user_pass.parent().parent();
    err_msg="";
    if(user_name.val().length<4){
        name_group.addClass("has-error");
        err_msg="- 用户名不能少于4个字符";
    }else{
        name_group.removeClass("has-error");
        name_group.addClass("has-success")
    }
    if(user_pass.val().length<6){
        pass_group.addClass("has-error");
        if(err_msg.length>0){err_msg+="<br>";}
        err_msg+="- 密码不能少于6个字符";
    }else{
        pass_group.removeClass("has-error");
        pass_group.addClass("has-success")
    }

    if(user_pass.val().length>5&&user_name.val().length>3){
        btn_submit.attr("disabled",false);
        $("#alert-info").hide(800);
        return true;
    }else{
        btn_submit.attr("disabled",true);
        $("#alert-info").html(err_msg);
        $("#alert-info").show(800);
        return false;
    }
}

/**
 * form login
 * check() is true post form
 * @returns {boolean}
 */
function login(){
    var spinner = new Spinner(opts);
    var timeout = setTimeout(function(){
        spinner.stop();
        $(".login-box-msg").html('商家用户请输入用户ID');
        Alert("服务器无响应，请稍候再试", true);
        $("#btn_submit").attr("disabled", false);
        $("#btn_submit").html('登陆');
    }, 5000);

    if (check_form()) {
        $(".login-box-msg").html('');
        spinner.spin($('.login-box-msg').get(0));
        $("#btn_submit").html('正在登陆...');
        $("#btn_submit").attr("disabled",true);

        $.post('/login', {
            user_name:  $("#user_name").val(),
            user_pass:  $("#user_pass").val(),
            _xsrf:  $("[name='_xsrf']").val(),
            next: $("#next").val(),
            isAjax: 1,
            remember: $("#remember").is(':checked') ? 1 : 0
        }, function(res, stat){
            spinner.stop();
            if (timeout) {
                clearTimeout(timeout);
                timeout = null;
            }
            $(".login-box-msg").html('商家用户请输入用户ID');
            if (stat !== 'success') {
               Alert("请求失败，请稍候再试", true);
               $("#btn_submit").attr("disabled", false);
               $("#btn_submit").html('登陆');
               return;
            }
            data = $.parseJSON(res);
            if (parseInt(data.err) === 0) {
                $("#btn_submit").addClass("btn-success");
                Alert('登录成功，正在跳转...');
                location.href = data.href;
            } else {
                Alert(data.msg, true);
                $("#btn_submit").attr("disabled", false);
                $("#btn_submit").html('登陆');
            }
        });
    }
    return false;
}

$(function(){
    if (parent !== undefined && parent.location.href !== location.href) {
        parent.location.href = location.href;
    }
    $("#alert-info").hide(500);
    $("#user_name").change(check_form);
    $("#user_pass").change(check_form);
    $("#btn_submit").click(login);

    // 密码输入框回车
    $('input.form-control').keyup(function (e) {
        if (e.keyCode === 13) {
            $("#btn_submit").click();
        }
    });
});